package com.hsmw.api.controller.biz;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hsmw.api.mapper.*;
import com.hsmw.api.service.HsmwDictDataService;
import com.hsmw.api.service.HsmwUserService;
import com.hsmw.api.service.HsmwVehicleService;
import com.hsmw.api.utils.GaoDeInfoUtils;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.BasePage;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.HsmwVehicle;
import com.hsmw.domain.form.GetObjectByIdForm;
import com.hsmw.domain.vo.GpsInfoEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.hsmw.common.base.BaseController;

import javax.validation.Valid;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.FAIL;

/**
 * <p>
 * 车辆信息表 前端控制器
 * </p>
 *
 * @author WD
 * @since 2021-02-07
 */
@Api(tags = "BIZ-车辆管理")
@RestController
@RequestMapping("/api/biz/vehicle")
public class BizVehicleController extends BaseController<HsmwUserService, HsmwUser> {

	@Autowired
	private HsmwVehicleService hsmwVehicleService;
	@Autowired
	HsmwVehicleMapper hsmwVehicleMapper;
	@Autowired
	private HsmwUserDriverMapper hsmwUserDriverMapper;
	@Autowired
	private HsmwDictDataService hsmwDictDataService;
	@Autowired
	private HsmwOrderVehicleRelationMapper hsmwOrderVehicleRelationMapper;

	@Autowired
	private HsmwReportMapper hsmwReportMapper;

	@Autowired
	private HsmwVehicleRefuelingMapper hsmwVehicleRefuelingMapper;

	@Autowired
	private HsmwComplainMapper hsmwComplainMapper;

	//public Long sumCount = 0L;

	/**
	 * 分页
	 *
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "获取车辆分页列表", notes = "获取车辆分页列表", produces = "application/json")
	@PostMapping("/getVehiclePage")
	public DataResponse getVehiclePage(@RequestBody @Valid BasePage<HsmwVehicle> basePage) {
		IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
		HsmwVehicle hsmwVehicle = basePage.getRequestData();
		IPage<HsmwVehicle> data = hsmwVehicleService.getVehiclePage(page, hsmwVehicle);
		List<String> vehicleIds = data.getRecords().stream().map(HsmwVehicle::getId).collect(Collectors.toList());
		if (CollectionUtil.isNotEmpty(vehicleIds)) {
			List<HsmwUserDriver> hsmwUserDrivers = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class).in(HsmwUserDriver::getVehicleId, vehicleIds));
			if (CollectionUtil.isNotEmpty(vehicleIds)) {
				Map<String, List<HsmwUserDriver>> map = hsmwUserDrivers.stream().collect(Collectors.groupingBy(HsmwUserDriver::getVehicleId));
				data.getRecords().forEach(vehicle -> {
					if (map.get(vehicle.getId()) != null) {
						vehicle.setBindDriverCount(map.get(vehicle.getId()).size());
					} else {
						vehicle.setBindDriverCount(0);
					}
				});
			}
		}
		return new DataResponse(data);
	}


	/**
	 * 根据ID查询数据
	 *
	 * @param form
	 * @return
	 */
	@ApiOperation(value = "根据id查询数据", notes = "根据id查询数据", produces = "application/json")
	@PostMapping("/getVehicleById")
	public DataResponse getVehicleById(@RequestBody GetObjectByIdForm form) {
		HashMap<Object, Object> resultMap = Maps.newHashMap();
		HsmwVehicle hsmwVehicle = hsmwVehicleService.getVehicleById(form.getKey());
		List<DriverAndVehicleVO> driverAndVehicleVOS = hsmwUserDriverMapper.findUserNameByVehicleIds(form.getKey());
		if (StringUtils.isNotBlank(hsmwVehicle.getImeiNum()) || StringUtils.isNotBlank(hsmwVehicle.getIdentifyingCode())) {
			GpsInfoEntity entity = GaoDeInfoUtils.getSingleVehicleGpsLocate(hsmwVehicle.getImeiNum(),hsmwVehicle.getFlag(),hsmwVehicle.getIdentifyingCode());
			if (StringUtils.isNotNull(entity) && StringUtils.isNotBlank(entity.getGpsLon())) {
				hsmwVehicle.setImeiNumLocate(entity.getGpsLon() + "," + entity.getGpsLat());
			}
			if(StringUtils.isNotBlank(hsmwVehicle.getImeiNumLocate())){
				String nameByGps = GaoDeInfoUtils.gaodeGetNameByGps(hsmwVehicle.getImeiNumLocate());
				hsmwVehicle.setVehicleAddress(nameByGps);
			}
		}else {
			hsmwVehicle.setImeiNumLocate(hsmwVehicle.getMobileLocate());
			String nameByGps = GaoDeInfoUtils.gaodeGetNameByGps(hsmwVehicle.getImeiNumLocate());
			hsmwVehicle.setVehicleAddress(nameByGps);
		}
		DriverInfoVO driverInfoVO = new DriverInfoVO();
		driverInfoVO.setVehicleId(form.getKey());
		IPage<DriverInfoVO> driverInfoVOIPage = hsmwUserDriverMapper.getBizHsmwDriverPage(new Page<>(1, Integer.MAX_VALUE), driverInfoVO);
		Double sumDriverVolume1 =  0.0;
		Double sumComfirmVolume = 0.0;
		List<RelationOrderVo> relationOrderVos = hsmwVehicleMapper.findRelationOrderListByVehicleId(form.getKey(),form.getMonth());
		Long sumComplainCount = 0L;
		for (RelationOrderVo relationOrderVo : relationOrderVos) {

			String relationId = relationOrderVo.getRelationId();
			List<HsmwComplain> hsmwComplains = hsmwComplainMapper.selectList(new LambdaQueryWrapper<HsmwComplain>().eq(HsmwComplain::getOrderId, relationId));
			if(CollectionUtil.isNotEmpty(hsmwComplains)){
				sumComplainCount += hsmwComplains.size();
			}

			String vehicleId = relationOrderVo.getVehicleId();
			List<DriverAndVehicleVO> list = hsmwUserDriverMapper.findUserNameByVehicleIds(vehicleId);
			relationOrderVo.setDriverAndVehicleVOS(list);
			//要求到达时间
			LocalDateTime reachTime = relationOrderVo.getReachTime();
			//实际到达时间
			LocalDateTime realReachTime = relationOrderVo.getRealReachTime();
			//结束时间
			LocalDateTime endTime = relationOrderVo.getEndTime();
			// 司机方量
			Double driverVolume = Double.valueOf(relationOrderVo.getDriverVolume() == null ? "0.0" : relationOrderVo.getDriverVolume());
			LocalDateTime startWorkTime = null;
			if(realReachTime != null && reachTime!=null){
				if(realReachTime.isBefore(reachTime)){
					startWorkTime = (reachTime.plusHours(2));
					relationOrderVo.setStartWorkTime(startWorkTime);
					if(driverVolume == 0){
						relationOrderVo.setConfirmVolume("0");
						relationOrderVo.setWorkTime(0L);
						continue;
					}
					if(endTime != null){
						Long endTimeSecond  = endTime.toEpochSecond(ZoneOffset.of("+8"));
						Long reachTimeSecond  = reachTime.toEpochSecond(ZoneOffset.of("+8"));
						long hours = 0;
						if((endTimeSecond-reachTimeSecond)%3600>0){
							hours = ((endTimeSecond - reachTimeSecond) / 3600) + 1;
						}else {
							hours = ((endTimeSecond - reachTimeSecond) / 3600);
						}
						relationOrderVo.setWorkTime(hours);
						if(hours > 10){
							Long aLong = 100L;
							aLong = aLong + (hours - 10)*10;
							if(aLong > driverVolume){
								relationOrderVo.setConfirmVolume(String.valueOf(aLong));
							}else {
								relationOrderVo.setConfirmVolume(String.valueOf(driverVolume));
							}
						}else {
							Long aLong = 100L;
							if(aLong > driverVolume){
								relationOrderVo.setConfirmVolume(String.valueOf(aLong));
							}else {
								relationOrderVo.setConfirmVolume(String.valueOf(driverVolume));
							}
						}
					}
				}else {
					//反之，为实际到达时间后两个小时
					//结束时间 减去 上述开始时间 如果大于10小时 如：十三个小时 一个小时保底为 10，不满一个小时按照一个小时计算
					startWorkTime = (realReachTime.plusHours(2));
					relationOrderVo.setStartWorkTime(startWorkTime);
					if(driverVolume == 0){
						relationOrderVo.setConfirmVolume("0");
						relationOrderVo.setWorkTime(0L);
						continue;
					}
					if(driverVolume == 0){
						relationOrderVo.setConfirmVolume("0");
					}else if(driverVolume < 100 && driverVolume > 0){
						relationOrderVo.setConfirmVolume("100");
					}else {
						relationOrderVo.setConfirmVolume(String.valueOf(driverVolume));
					}
					if(endTime != null){
						Long endTimeSecond  = endTime.toEpochSecond(ZoneOffset.of("+8"));
						Long realReachTimeSecond  = realReachTime.toEpochSecond(ZoneOffset.of("+8"));
						long hours = 0;
						if((endTimeSecond-realReachTimeSecond)%3600>0){
							hours = ((endTimeSecond - realReachTimeSecond) / 3600) + 1;
						}else {
							hours = ((endTimeSecond - realReachTimeSecond) / 3600);
						}
						relationOrderVo.setWorkTime(hours);
						if(hours > 10){
							Long aLong = 100L;
							aLong = aLong + (hours - 10)*10;
							if(aLong > driverVolume){
								relationOrderVo.setConfirmVolume(String.valueOf(aLong));
							}else {
								relationOrderVo.setConfirmVolume(String.valueOf(driverVolume));
							}
						}else {
							Long aLong = 100L;
							if(aLong > driverVolume){
								relationOrderVo.setConfirmVolume(String.valueOf(aLong));
							}else {
								relationOrderVo.setConfirmVolume(String.valueOf(driverVolume));
							}
						}
					}
				}
			}else {
				relationOrderVo.setConfirmVolume("0");
			}

			String confirmVolume = relationOrderVo.getConfirmVolume();
			String driverVolume1 = relationOrderVo.getDriverVolume();
			sumDriverVolume1 += Double.valueOf(driverVolume1);
			sumComfirmVolume += Double.valueOf(confirmVolume);
		}
		String sumDriverVolume = String.format("%.1f", sumDriverVolume1);
		Integer vehicleFaultCount = hsmwReportMapper.selectCount(new LambdaQueryWrapper<HsmwReport>().eq(HsmwReport::getVehicleId, form.getKey()).eq(HsmwReport::getReportType, "2"));

		Integer trafficAccidentCount = hsmwReportMapper.selectCount(new LambdaQueryWrapper<HsmwReport>().eq(HsmwReport::getVehicleId, form.getKey()).eq(HsmwReport::getReportType, "3"));

		resultMap.put("sumComplainCount",sumComplainCount);
		resultMap.put("vehicleFaultCount",vehicleFaultCount);
		resultMap.put("trafficAccidentCount",trafficAccidentCount);
		resultMap.put("hsmwVehicle", hsmwVehicle);
		resultMap.put("hsmwUserDrivers", driverInfoVOIPage.getRecords());
		resultMap.put("driver",driverAndVehicleVOS);
		resultMap.put("SumDriverVolume",sumDriverVolume);
		resultMap.put("SumConfirmVolume",sumComfirmVolume);
		resultMap.put("orderList",relationOrderVos);
		return new DataResponse(resultMap);
	}

	/**
	 * 新增
	 * 修改  必须带ID
	 *
	 * @param hsmwVehicle
	 * @return
	 */
	@ApiOperation(value = "新增/修改", notes = "新增：传对象；修改：传id；", produces = "application/json")
	@PostMapping("/saveOrUpdateVehicle")
	public DataResponse saveOrUpdateVehicle(@RequestBody @Valid HsmwVehicle hsmwVehicle) {
		HsmwVehicle hsmwVehicles = hsmwVehicleMapper.selectOne(new LambdaQueryWrapper<HsmwVehicle>().eq(HsmwVehicle::getVehiclePlate, hsmwVehicle.getVehiclePlate()));
		if(StringUtils.isNotNull(hsmwVehicles) && !StringUtils.equals(hsmwVehicle.getId(),hsmwVehicles.getId())){
			return new DataResponse(FAIL,"车牌号重复，请重新输入！");
		}
		if(hsmwVehicle.getDrivingLicenseTime().isBefore(LocalDate.now()) && hsmwVehicle.getCommercialInsuranceTime().isBefore(LocalDate.now()) && hsmwVehicle.getCompuTrafficTime().isBefore(LocalDate.now())){
			return new DataResponse(FAIL,"日期输入错误，日期不能小于今天时间，请检查！");
		}
		return new DataResponse(hsmwVehicleService.saveOrUpdateVehicle(hsmwVehicle));
	}

	/**
	 * 车辆数据汇总
	 *
	 * @param basePage
	 * @return
	 */
	@ApiOperation(value = "车辆数据汇总", notes = "车辆数据汇总", produces = "application/json")
	@PostMapping("/getVehicleDataCollect")
	public DataResponse getVehicleDataCollect(@RequestBody @Valid BasePage<VehicleDataCollectVO> basePage) {
		IPage page = new Page(basePage.getPageNo(), basePage.getPageSize());
		VehicleDataCollectVO queryData = basePage.getRequestData();
		IPage<VehicleDataCollectVO> vehiclePage = hsmwVehicleService.getVehicleDataCollect(page, basePage.getRequestData());
		if (queryData.getQueryDate() == null) {
			queryData.setQueryDate(new Date());
		}
//		Page<VehicleDataCollectVO> vehicleDataCollectDtoList = hsmwVehicleMapper.selectVehicleMonthOrderCount(page, DateUtil.beginOfMonth(queryData.getQueryDate()), DateUtil.endOfMonth(queryData.getQueryDate()), queryData.getVehiclePlate(), queryData.getVehicleModel());
		Set<String> vehicleIdSet = vehiclePage.getRecords().stream().map(HsmwVehicle::getId).collect(Collectors.toSet());
		if (CollectionUtil.isNotEmpty(vehicleIdSet)) {
			Map<String, List<HsmwOrderVehicleRelation>> orderVehicleMap = hsmwOrderVehicleRelationMapper.selectList(
					Wrappers.lambdaQuery(HsmwOrderVehicleRelation.class)
							.in(HsmwOrderVehicleRelation::getVehicleId, vehicleIdSet)
							.between(HsmwOrderVehicleRelation::getEndTime, DateUtil.beginOfMonth(queryData.getQueryDate()), DateUtil.endOfMonth(queryData.getQueryDate())))
					.stream().collect(Collectors.groupingBy(HsmwOrderVehicleRelation::getVehicleId));
			vehiclePage.getRecords().forEach(vehicleDataCollectVO -> {
				vehicleDataCollectVO.setQueryDate(queryData.getQueryDate());
				if (orderVehicleMap.get(vehicleDataCollectVO.getId()) != null) {
					vehicleDataCollectVO.setOrderMontyCount(orderVehicleMap.get(vehicleDataCollectVO.getId()).size());
					Integer volumeMontyCount = orderVehicleMap.get(vehicleDataCollectVO.getId()).stream()
							.map(HsmwOrderVehicleRelation::getDriverVolume)
							.filter(StrUtil::isNotBlank)
							.map(Integer::parseInt)
							.reduce(0, (a, b) -> a + b);
					vehicleDataCollectVO.setVolumeMontyCount(volumeMontyCount);
				}
			});
		}
		return new DataResponse(vehiclePage);
	}

	/**
	 * @param
	 * @return
	 */
	@ApiOperation(value = "根据type获取字典下面的数据", notes = "获取字典数据  传dictLabel", produces = "application/json")
	@PostMapping("/getDictDataByParent")
	public DataResponse getDictDataByParent(@RequestBody JSONObject jsonObject) {
		List<HsmwDictData> result = hsmwDictDataService.getDictDataByParent(jsonObject.getStr("dictLabel"));
		return new DataResponse(result);
	}

	/**
	 * 车辆与司机解除绑定
	 */
	@ApiOperation(value = "车辆与司机解除绑定",notes = "车辆与司机解除绑定",produces = "application/json")
	@ApiImplicitParam(name = "userId",value = "用户id",dataType = "String")
	@PostMapping("/unbindDriverUserAndVehicle")
	public DataResponse unbindDriverUserAndVehicle(String userId){

		return new DataResponse(hsmwDictDataService.unbindDriverUserAndVehicle(userId));
	}

	/**
	 * 删除车辆
	 */
	@ApiOperation(value = "删除车辆",notes = "删除车辆",produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "driverId",value = "车辆id",dataType = "String")
	})
	@PostMapping("/delDriverById")
	public DataResponse delDriverById(String driverId){

		return new DataResponse(hsmwDictDataService.delDriverById(driverId));
	}


	/**
	 * 查询所有的司机
	 */
	@ApiOperation(value = "查询所有的司机",notes = "查询所有的司机",produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "vehicleId",value = "车辆id",dataType = "String")
	})
	@PostMapping("/driverList")
	public DataResponse driverList(String vehicleId){
		HashMap param = new HashMap();
		param.put("vehicleId",vehicleId);
		List<DriverInfoDTO> allDrivers = hsmwUserDriverMapper.selectAllDriversList(param);
		List<DriverInfoDTO> vehicleDrivers = hsmwUserDriverMapper.selectDriversList(param);
		HashMap map = new HashMap();
		map.put("allDrivers",allDrivers);
		map.put("vehicleDrivers",vehicleDrivers);
		return new DataResponse(map);
	}


	/**
	 * 更新车辆的司机信息
	 */
	@ApiOperation(value = "更新车辆的司机信息",notes = "更新车辆的司机信息",produces = "application/json")
	@PostMapping("/tranfervehicle")
	public DataResponse tranfervehicle(@RequestBody VehicleTranferVO vehicleTranferVO){
		if(StringUtils.isBlank(vehicleTranferVO.getVehicleId())){
			return new DataResponse(FAIL,"您输入的车辆ID为空，请重新输入！");
		}
		/*if(StringUtils.isBlank(vehicleTranferVO.getDriverIds())){
			return new DataResponse(FAIL,"您输入的司机IDs为空，请重新输入！");
		}*/
		try {
			return hsmwVehicleService.tranfervehicle(vehicleTranferVO);
		}catch (Exception e){
			e.printStackTrace();
			return new  DataResponse(CommonConstants.ResponseStatus.SYSTEM_ERROR,"更新车辆的司机信息，请联系系统管理员！");
		}
	}

	@ApiOperation(value = "车辆月统计方量", notes = "车辆月统计方量", produces = "application/json")
	@ApiImplicitParam(name = "id",value = "车辆id",dataType = "String")
	@PostMapping("/findVehicleVolumeByMonth")
	public DataResponse findVehicleVolumeByMonth(String id,String month){
		Map map = new HashMap();
		StringBuffer stringBuffer = new StringBuffer(month);
		StringBuffer append = stringBuffer.append("-01");
		String s = LocalDate.now().toString();
		String[] split = s.split("-");
		String s1 = split[0];
		StringBuffer buffer = new StringBuffer(s1+"-");
		StringBuffer date = buffer.append(append);
		String s2 = date.toString();
		LocalDate localDate = LocalDate.parse(s2, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		//这个月的第一天
		Date monthStart = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
		//这个月的最后一天 下个月的第一天
		Date monthEnd = Date.from(localDate.with(TemporalAdjusters.lastDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
		DateTime endTime = DateUtil.date(monthEnd);
		DateTime startTime = DateUtil.date(monthStart);
		List<HomeVolume> homeVolumes = hsmwVehicleMapper.findVehicleVolumeByMonth(id,month);
		List<String> dayBetween = com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(endTime.toJdkDate(), "yyyy-MM-dd"));
		map.put("month",dayBetween);
		map.put("homeVolume",homeVolumes);
		return new DataResponse(map);
	}


	@ApiOperation(value = "车辆项目占比 按周 月  分组", notes = "车辆项目占比 按周 月  分组", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "params", value = "月份", dataType = "String"),
			@ApiImplicitParam(name = "id", value = "车辆id", dataType = "String"),
	})
	@PostMapping("findItemPercentageByVehicleId")
	public DataResponse findItemPercentageByVehicleId(String id, String params) {

		if (StringUtils.isBlank(params)) {
			return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数错误");
		}
		Map map = new HashMap();

		List<HomeVolume> homeVolumes = hsmwVehicleMapper.findItemPerOnMonth(id,params);
		map.put("homeVolumes", homeVolumes);

		return new DataResponse(map);
	}

	@ApiOperation(value = "车辆加油统计", notes = "车辆加油统计", produces = "application/json")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "params", value = "按周:1 月:2 年:3 分组", dataType = "String"),
			@ApiImplicitParam(name = "id", value = "车辆id", dataType = "String"),
	})
	@PostMapping("/findVehicleRefuelingById")
	public DataResponse findVehicleRefuelingById(String params,String id){
		if (StringUtils.isBlank(params)) {
			return new DataResponse(CommonConstants.ResponseStatus.FAIL, "参数错误");
		}
		Map map = new HashMap();
		AtomicReference<Long> sumCount = new AtomicReference<>(0L);
		if (StringUtils.equals("1", params)) {

			List<HomeVolume> homeVolumes = hsmwVehicleRefuelingMapper.findFulVolumeWeek(id);
			homeVolumes.stream().forEach(homeVolume -> {
				String[] weekDays = { "周天", "周一", "周二", "周三", "周四", "周五", "周六" };
				Calendar cal = Calendar.getInstance();
				Date date = new Date();
				cal.setTime(date.from(homeVolume.getEndTime().atZone( ZoneId.systemDefault()).toInstant()));
				int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
				if (w < 0)
					w = 0;
				homeVolume.setWeekName(weekDays[w]);
				if(homeVolume.getForemanVolume() == null){
					homeVolume.setForemanVolume("0");
				}
				sumCount.updateAndGet(v -> v + Double.valueOf(homeVolume.getForemanVolume()).longValue());
			});
			map.put("orderTrend",homeVolumes);
			map.put("sumCount",sumCount.get());

		}

		if (StringUtils.equals("2", params)) {
			List<JSONObject> orderTrend = Lists.newArrayList();
			LocalDate localDate = LocalDate.now();
			//这个月的第一天
			Date monthStart = Date.from(localDate.with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());
			//这个月的最后一天 下个月的第一天
			Date monthEnd = Date.from(localDate.plusMonths(1).with(TemporalAdjusters.firstDayOfMonth()).atStartOfDay(ZoneId.systemDefault()).toInstant());

			DateTime endTime = DateUtil.date(monthEnd);
			DateTime startTime = DateUtil.date(monthStart);
			List<HsmwVehicleRefueling> hsmwOrderList = hsmwVehicleRefuelingMapper.selectList(
					Wrappers.lambdaQuery(HsmwVehicleRefueling.class)
							.between(HsmwVehicleRefueling::getSubmitTime, DateUtil.beginOfDay(startTime), DateUtil.endOfDay(endTime)).eq(HsmwVehicleRefueling::getVehicleId,id)
			);
			hsmwOrderList.forEach(x -> x.setStatisticsTime(DateUtil.format(Date.from(x.getSubmitTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd")));

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(endTime);
			calendar.add(Calendar.DATE,-1);
			Date dateEndtime =calendar.getTime();
			Map<String, List<HsmwVehicleRefueling>> statisticsMap = hsmwOrderList.stream().collect(Collectors.groupingBy(HsmwVehicleRefueling::getStatisticsTime));
			List<String> dayBetween = com.htn.common.core.utils.DateUtil.getDayBetween(DateUtil.format(startTime.toJdkDate(), "yyyy-MM-dd"), DateUtil.format(dateEndtime, "yyyy-MM-dd"));

			for (String day : dayBetween) {
				AtomicInteger count = new AtomicInteger();
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("day", day);
				if (statisticsMap.get(day) != null) {
					List<HsmwVehicleRefueling> orderList = statisticsMap.get(day);
					orderList.stream().forEach(x -> {
						if (StrUtil.isNotBlank(x.getFuelVolume())) {
							String foremanVolume = x.getFuelVolume();
							count.addAndGet(Integer.valueOf(foremanVolume));
						}
					});
				}
				jsonObject.put("count", count);
				orderTrend.add(jsonObject);
			}
			map.put("orderTrend",orderTrend);
			hsmwOrderList.stream().forEach(hsmwOrder -> {
				sumCount.updateAndGet(v -> v + Long.parseLong(hsmwOrder.getFuelVolume()));
			});
			map.put("sumCount",sumCount.get());
		}


		return new DataResponse(map);
	}

	@ApiOperation(value = "删除车辆信息", notes = "删除车辆信息；", produces = "application/json")
	@PostMapping("/deleteVehicleById")
	public DataResponse deleteVehicleById(@RequestBody GetObjectByIdForm form){

		if(form.getKey() == null){
			return new DataResponse(CommonConstants.ResponseStatus.FAIL,"id不能为空");
		}
		boolean del = hsmwVehicleService.removeById(form.getKey());
		if(del){
			return new DataResponse(CommonConstants.ResponseStatus.SUCCESS,"删除成功");
		}
		return new DataResponse(CommonConstants.ResponseStatus.FAIL,"删除失败");

	}

}

